package com.travel.member.interceptor;

import com.alibaba.fastjson.JSON;
import com.travel.common.constant.AuthServerConstant;
import com.travel.common.vo.MemberRespVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.travel.common.constant.AuthServerConstant.LOGIN_USER;

@Component
public class LoginUserInterceptor implements HandlerInterceptor {

    public static ThreadLocal<MemberRespVo> loginUser = new ThreadLocal<>();

    StringRedisTemplate redisTemplate;

    public LoginUserInterceptor(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 其它微服务调用会员服务，不用登录状态，直接放行
        String uri = request.getRequestURI();
        boolean match = new AntPathMatcher().match("/member/**", uri);
        if(match){
            return true;
        }

        // 从redis获取用户信息
        String s = redisTemplate.opsForValue().get(LOGIN_USER);
        MemberRespVo memberRespVo = JSON.parseObject(s,MemberRespVo.class);
        if(memberRespVo != null){
            //登录了，把用户信息放在ThreadLocal中
            loginUser.set(memberRespVo);
            //放行
            System.out.println(memberRespVo);
            return true;
        }else{
            //没登录，去登录
            request.getSession().setAttribute("msg","请先进行登录");
            response.sendRedirect("http://auth.travel.com/login.html");
            return false;
        }
    }

}
